package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import com.example.demo.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;

/**
 * Copyright (C), 2015-2019
 * FileName: SystemController
 * Author:   MRC
 * Date:     2019/8/17 12:31
 * Description: 系统控制器
 * History:
 */
@Controller
@RequestMapping
public class SystemController {

    @Autowired
    private AipOcr aipOcr;

    @Value("${upload.img.path}")
    private String imagePath;

    @Value("${api.baidu.com.template}")
    private String templateCode;

    /**
     * @Author MRC
     * @Description 页面路由
     * @Date 12:31 2019/8/17
     * @Param []
     * @return java.lang.String
     **/
    @RequestMapping("index")
    public String index() {
        return "index";
    }


    /**
     * @Author MRC
     * @Description 上传
     * @Date 16:23 2019/8/17
     * @Param [file]
     * @return com.alibaba.fastjson.JSONObject
     **/
    @RequestMapping("/upload")
    @ResponseBody
    public JSONObject singleFileUpload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return JsonUtil.getFailJson("上传文件不能为空");
        }

        File paths = new File(imagePath);
        //不存在则创建
        if (!paths.exists()) {
            paths.mkdir();
        }

        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(imagePath + file.getOriginalFilename());
            Files.write(path, bytes);

            return JsonUtil.getSuccessJson("上传成功","/image/"+path.getFileName());
        } catch (IOException e) {
            return JsonUtil.getFailJson("服务器错误");
        }

    }


    /**
     * @Author MRC
     * @Description 文件上传后的识别功能
     * @Date 16:26 2019/8/17
     * @Param [path]
     * @return com.alibaba.fastjson.JSONObject
     **/
    @RequestMapping("distinguish")
    @ResponseBody
    public JSONObject distinguish(String path){

        HashMap<String, String> options = new HashMap<String, String>();
        options.put("templateSign", templateCode);

        // 参数为本地路径
        org.json.JSONObject res = aipOcr.custom("C:"+path,templateCode,options);

        System.out.println(res.toString(2));

        return JsonUtil.getSuccessJson("识别成功",res.toString(2));
    }

}